#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const puppeteer = require('puppeteer');

// 从文件读取 URL 列表
function readUrls(file) {
  if (!fs.existsSync(file)) {
    console.error(`❌ 找不到文件: ${file}`);
    process.exit(1);
  }
  return fs.readFileSync(file, 'utf-8')
    .split('\n')
    .map(line => line.trim())
    .filter(Boolean);
}

// 生成文件名：时间戳 + 域名
function makeFileName(url) {
  const hostname = new URL(url).hostname.replace(/\./g, '_');
  return `${Date.now()}_${hostname}.png`;
}

// 批量截图
async function captureAll(urls, concurrency = 3) {
  const browser = await puppeteer.launch({
    headless: true,
    args: ['--no-sandbox']
  });

  const chunks = [];
  for (let i = 0; i < urls.length; i += concurrency) {
    chunks.push(urls.slice(i, i + concurrency));
  }

  for (const chunk of chunks) {
    await Promise.all(chunk.map(async (url) => {
      try {
        const page = await browser.newPage();
        await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
        await page.goto(url, { waitUntil: 'networkidle2', timeout: 30000 });
        
        const fileName = makeFileName(url);
        const filePath = path.join(__dirname, fileName);
        await page.screenshot({ path: filePath, fullPage: true });

        console.log(`✅ 截图完成: ${url} → ${fileName}`);
        await page.close();
      } catch (err) {
        console.error(`❌ 截图失败: ${url}`, err.message);
      }
    }));
  }

  await browser.close();
}

(async () => {
  const file = process.argv[2] || 'urls.txt';
  const urls = readUrls(file);
  if (!urls.length) {
    console.error('❌ URL 列表为空');
    process.exit(1);
  }
  console.log(`📸 共 ${urls.length} 个网址，开始截图...`);
  await captureAll(urls, 3); // 3 个并发
})();
